package com.web;

import com.google.gson.Gson;
import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.test.UserServletTest;
import com.uitl.WebUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @Discription:
 */
public class UserServlet extends BaseServlet {
    private UserService userService=new UserServiceImpl();

    //处理登录的功能
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //调用XXXservice.login处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        //如果等于null说明登录失败
        if (loginUser==null){
            //把错误信息，和回显的表单项信息，保存到request域中
            req.setAttribute("msg","用户名或密码错误");
            req.setAttribute("username",username);
            System.out.println("用户名或密码错误，登录失败");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else{
            //登录成功
            req.getSession().setAttribute("user",loginUser);//保存用户登录之后的信息到Session域中

            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }
    }

    //处理注册的功能
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取Session种的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session种的验证码，使用一次后马上删除，可以防止用户回退导致的多次输入数据库
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //获取参数:获取的参数对应着表单的name属性值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");


        User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());

        //2、检查验证码是否正确（这里先写死检查，验证码为：1234）
        if (token!=null && token.equalsIgnoreCase(code)){
            //检查用户名是否正确
            if (userService.exitsUsername(username)){
                //不可用
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                System.out.println("用户名["+username+"]已存在");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else{
                userService.registUser(new User(null,username,password,email));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }

        }else {
            //验证码不正确,跳回注册页面
            //把回显信息保存到request域中
            req.setAttribute("msg","输入验证码有误");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码["+code+"]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }

    //注销
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、销毁 Session 中用户登录的信息（或者销毁 Session）
        req.getSession().invalidate();
        //2、重定向到首页（或登录页面）。
        resp.sendRedirect(req.getContextPath());
    }

    protected void ajaxExistUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数username
        String username = req.getParameter("username");
        //调用userService.existUsername
        boolean exitsUsername = userService.exitsUsername(username);
        //把返回的结果封装成为map对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("exitsUsername",exitsUsername);//将数据封装到map当中
        //导入Gson包，将数据以json字符串的形式传送给客户端
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

}
